package com.wx.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DownloadImgUtil {
	private static final Logger logger = LoggerFactory.getLogger(DownloadImgUtil.class);
	
	public static byte[] fetchStream(String url){
		InputStream is = null;
		boolean isUri = true;
		try{
			new URL(url);
		} catch (Exception e){
			isUri = false;
		}
		try{
			HttpClient client = new HttpClient();
			HttpConnectionManagerParams params = client.getHttpConnectionManager().getParams();
			params.setConnectionTimeout(5000);
			params.setSoTimeout(5000);
			client.getHttpConnectionManager().setParams(params);
			GetMethod get = new GetMethod(url);
			int code = client.executeMethod(get);
			if(code==200){
				is = get.getResponseBodyAsStream();
				byte[] btImg = readInputStream(is);//得到图片的二进制数据  
	            return btImg;
			}else{
				throw new HttpException("文件服务器请求异常，响应代码["+code+"]");
			}
		} catch (Exception e){
			e.printStackTrace();
			logger.error("请求文件服务器错误:"+e.getMessage());
		}finally{
			if(null!=is){
				try{
					is.close();
				} catch (IOException e){
					e.printStackTrace();
				}
			}
		}
		return null;
	}
	
	/** 
     * 从输入流中获取数据 
     * @param inStream 输入流 
     * @return 
     * @throws Exception 
     */  
    public static byte[] readInputStream(InputStream is) throws Exception{  
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
        byte[] buffer = new byte[1024];  
        int len = 0;  
        while( (len=is.read(buffer)) != -1 ){  
            outStream.write(buffer, 0, len);  
        }  
        is.close();  
        return outStream.toByteArray();  
    }  
}
